<?php
namespace app\admin\controller;

use app\common\controller\ContentController;
use app\common\logic\AdminLogic;
use app\common\logic\ContentLogic;
use app\common\logic\GoodsLogic;
use app\common\service\GoodsService;
use gdbase\Tree2;
use think\facade\Validate;

/**
 * models 模型重写示例 ， 可删除
 * Class Goods
 * @package app\admin\controller
 */
class Goods extends ContentController
{
    private $listIsDel = 0;

    public function initialize(){
        $this->controllerName = '商品';
        $this->modelId = 4;
        parent::initialize();
        $this->modelName = 'Goods';
    }

    /**
     * 分类添加的时候 处理需要显示的表单
     * @param $formFields
     * @return array
     */
    protected function handleCategoryAddFormFields(&$formFields){
        // 不显示 栏目图片
//        unset($formFields['image_url']);
        // 不显示 栏目描述
        unset($formFields['description']);
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }
    /**
     * 分类编辑的时候 处理需要显示的表单
     * @param $formFields
     * @return array
     */
    protected function handleCategoryEditFormFields(&$formFields){
        // 不显示 栏目图片
//        unset($formFields['image_url']);
        // 不显示 栏目描述
        unset($formFields['description']);
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }

    public function index(){
        $show = input('show',1);
        /**
         * 查询条件
         */
        $whereKeys = [
            'goods_name' => [
                'key' => 'goods_name',
                'text' => '商品名称',
                'op' => 'LIKE',
                'type' => 'text',
            ],
            'cates' => [
                'key' => 'cates',
                'text' => '分类',
                'op' => ',LIKE,',
                'type' => 'select_source',
                'type_value_custom' => [
                    'source' => 'catList',
                    'tree_parent_id_name' => 'parent_id',
                    'is_tree' => true,
                ],
                'tree_parent_id_name' => 'parent_id',
                'is_tree' => true,
            ],
        ];

        $cLogic = new ContentLogic();
        $alj = new GoodsLogic($this->modelName);
        $paramWhere = $this->getParamWhere($whereKeys);
        $where[] = ['model_id','=',$this->modelId];
        // TODO: 按项目搜索
        $where[] = ['project_id','=',$this->getProjectId()];
        $data = $cLogic->_getCategorySelectData($where);
        // 加工分类，可以方便显示
        $listShowCategory = [];
        foreach ($data as $item){
            $listShowCategory[$item['id']] = $item['text'];
        }
        $this->addSelectList('catList',$data);

        //附加条件
        $this->listIsDel = 0;
        switch ($show) {
            case 4:
                $this->listIsDel = 1;
                break;
            default:
                $paramWhere['where'] = array_merge(getGoodsWhere($show,false),$paramWhere['where']);
                break;
        }
//        dump($paramWhere);exit;
        $pagerInfo = $this->getPagerInfo($alj->_getGoodsPagerCountByWhere($paramWhere['where'],$this->listIsDel),input('p',1),$paramWhere['search']);
        $dataList = $alj->_getGoodsPager($paramWhere['where'],$pagerInfo['offset'],$pagerInfo['pageSize'],'id DESC',$this->listIsDel);

        //补全数据
        foreach ($dataList as &$item) {
            // 处理分类
            if(!empty($item['cates'])){
                $item['cates'] = array_filter (explode(',',$item['cates']));
            }
        }

        $num = $alj->_getGoodsShowNum(['1','2','3','4']);

        $this->assign('showNum',$num);

        $this->assign('datas',$dataList);
        $this->assign('search',$paramWhere['search']);
        $this->assign('whereKeys',$whereKeys);
        $this->assign($pagerInfo);
        // 通过数据源设置的变量
        $this->assign('selectList',$this->getSelectList());

        $this->assign('listShowCategory',$listShowCategory);
        $this->assign('goodsSiteEnum',config('site_enum.goods'));
        $this->assign('show',$show);
        return $this->fetch();
    }

    public function add(){
        $param = input('param.');
        $goodsType = config('site_enum.goods.type');
        $goodsStatus = config('site_enum.goods.status');
        $goodsStockCnf = config('site_enum.goods.stock_cnf');

        $goodsLogic = new GoodsLogic();

        if (request()->isAjax()){
            if(empty($param['id'])){
                $param['id'] = 0;
            }
            $flag = $goodsLogic->saveGoods($param);
            if($flag['err_code'] === 0){
                $this->success($flag['msg'],url('edit',['id' => hashIdEncode($flag['data']['goods_id'])]));
            }
            else{
                $this->error($flag['msg']);
            }
        }
        $categorys = $goodsLogic->_getGoodsCategory($this->getProjectId());

        $this->assign('goodsType',$goodsType);
        $this->assign('goodsCategorys',Tree2::makeTree($categorys));
        $this->assign('goodsStatus',$goodsStatus);
        $this->assign('goodsStockCnf',$goodsStockCnf);

        return $this->fetch();
    }

    public function edit()
    {
        $param = input('param.');
        $goodsLogic = new GoodsLogic($this->modelName);
        if (request()->isAjax()){
            if(empty($param['id'])){
                $this->error('id参数错误');
            }
            $param['id'] = hashIdDecode($param['id']);
            if(empty($param['id'])){
                $this->error('id参数错误');
            }
//            dump($param);exit;
            $flag = $goodsLogic->saveGoods($param);

            if($flag['err_code']  === 0){
                $this->success($flag['msg'],url('edit',['id' => hashIdEncode($flag['data']['goods_id'])]));
            }
            else{
                $this->error($flag['msg']);
            }
        }

        $id = input('param.id');
        if (empty($id)){
            $this->error('参数错误',url('index'));
        }
        $id = hashIdDecode($id);
        if (empty($id)){
            $this->error('参数错误',url('index'));
        }

        $model = $goodsLogic->_getGoodsById($id);
        if(empty($model)){
            $this->error('找不到数据');
        }
        $pkName = db($this->modelName)->getPk();
        $model[$pkName] = hashIdEncode($model[$pkName]);

        $categorys = $goodsLogic->_getGoodsCategory($this->getProjectId());

        $goodsType = config('site_enum.goods.type');
        $goodsStatus = config('site_enum.goods.status');
        $goodsStockCnf = config('site_enum.goods.stock_cnf');

        $cates = [];

        if(!empty($model['cates'])){
            // 去掉空的
            $cates = explode(',',$model['cates']);
            $cates = array_filter ($cates);
        }
        $this->assign('cates',$cates);

        $this->assign('goodsType',$goodsType);
        $this->assign('goodsCategorys',Tree2::makeTree($categorys));
        $this->assign('goodsStatus',$goodsStatus);
        $this->assign('goodsStockCnf',$goodsStockCnf);

        // 处理规格输入框
        if(!empty($model['options'])){
            $fanhui = [];
            foreach ($model['options'] as $option) {
                $fanhui[] = [
                    'option_stock' => $option['stock'],
                    // 分 转 元
                    'option_marketprice' => fenToYuan($option['market_price']),
                    'option_productprice' => fenToYuan($option['product_price']),
                    'option_costprice' => fenToYuan($option['cost_price']),

                    'option_goodssn' => $option['goods_sn'],
                    'option_productsn' => $option['product_sn'],
                    'option_weight' => $option['weight'],
                    'id' => $option['id'],
                ];
            }
            $model['options'] = $fanhui;
        }

        $this->assign([
            'model' => $model,
        ]);

        return $this->fetch();
    }

    public function recovery(){
        $goodsLogic = new GoodsLogic($this->modelName);
        $id = input('param.id');
        if (empty($id)){
            $this->error('参数错误',url('index'));
        }
        $id = hashIdDecode($id);
        if (empty($id)){
            $this->error('参数错误',url('index'));
        }

        $jieguo = $goodsLogic->_recoveryGoodsById($id);

        if($jieguo !== false){
            $this->success('恢复成功');
        }
        else{
            $this->error('恢复失败');
        }
    }

    /**
     * 改变属性
     */
    public function change_attr(){
        $id = input('param.id');
        $status = input('param.status');
        $attr = input('param.attr');
        if (empty($id)){
            $this->error('id 参数错误');
        }
        $id = hashIdDecode($id);
        if (empty($id)){
            $this->error('id 参数错误2');
        }
        $goodsService = new GoodsService();
        $jieguo = $goodsService->getGoods($id);
        if($jieguo['err_code'] !== 0){
            $this->error('找不到数据');
        }
        $jieguo = $goodsService->changeGoodsAttr($id, $attr, $status);
        if($jieguo['err_code'] === 0){
            $this->success('成功');
        }
        else{
            $this->error('变更商品属性失败');

        }
    }
}
